package cn.wolfcode.crm.service.impl;

import cn.wolfcode.crm.domain.Permission;
import cn.wolfcode.crm.mapper.PermissionMapper;
import cn.wolfcode.crm.query.QueryObject;
import cn.wolfcode.crm.service.IPermissionService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.aop.support.AopUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;

import java.lang.reflect.Method;
import java.util.Collection;
import java.util.List;

@Service
public class PermissionServiceImpl implements IPermissionService {
    @Autowired
    private PermissionMapper permissionMapper;
    @Autowired
    private ApplicationContext ctx;


    public List<Permission> list() {
        return permissionMapper.selectAll();
    }

    public PageInfo<?> query(QueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize());
        List<?> list = permissionMapper.selectForList(qo);
        return new PageInfo<>(list);
    }

    public void reload() {
        // 查询系统中已有的表达式
        List<String> exps =  permissionMapper.queryAllExpressions();
        // 获取所有控制器对象
        Collection<Object> ctrls = ctx.getBeansWithAnnotation(Controller.class).values();
        // 遍历控制器对象
        for (Object ctrl : ctrls) {
            // 判断该对象是否是CGLIB的动态代理对象
            if (AopUtils.isCglibProxy(ctrl)) {
                // 拿到原始controller(代理对象所继承的类)中的每一个声明的方法
                Method[] ms = ctrl.getClass().getSuperclass().getDeclaredMethods();
                for (Method m : ms) {
                    // 迭代每一个方法获取shiro权限注解
                    RequiresPermissions annotation = m.getAnnotation(RequiresPermissions.class);
                    if (annotation!=null){
                        String name = annotation.value()[0];
                        String expression = annotation.value()[1];
                        if (!exps.contains(expression)){
                            // 该权限在数据库中不存在则报错到数据库
                            Permission permission = new Permission();
                            permission.setName(name);
                            permission.setExpression(expression);
                            permissionMapper.insert(permission);
                        }
                    }
                }
            }
        }
    }
}
